/*
** input.c for zomzom in /home/goupil_r//GameInLab/zomzom/src
**
** Made by robin goupil
** Login   <goupil_r@epitech.net>
**
** Started on  Fri Nov 16 16:51:15 2012 robin goupil
** Last update Sun Nov 18 16:21:54 2012 robin goupil
*/

#include <SDL/SDL.h>
#include "include/struct.h"
#include "include/player.h"
#include "include/shooting.h"
#include "include/world.h"
#define ABS(x) (x >= 0 ? x: x * -1)
#define SIGN(x) (x >= 0 ? 1 : -1)

void		move_player(t_player *player, int x, int y)
{
  player->biped->speed_x += (player->biped->acceleration * x);
  player->biped->speed_y += (player->biped->acceleration * y);
  if (ABS(player->biped->speed_x) > player->biped->max_speed)
    player->biped->speed_x = player->biped->max_speed * SIGN(player->biped->speed_x);
  if (ABS(player->biped->speed_y) > player->biped->max_speed)
    player->biped->speed_y = player->biped->max_speed * SIGN(player->biped->speed_y);
}

void		stop_player(t_player *player)
{
  player->biped->speed_x *= 0.95;
  player->biped->speed_y *= 0.95;
  if (ABS(player->biped->speed_x) < 0.05)
    player->biped->speed_x = 0;
  if (ABS(player->biped->speed_y) < 0.05)
    player->biped->speed_y = 0;
}

void		apply_speed_player(t_player *player, int x, int y)
{
  if (x != 0)
    player->biped->pos.x += player->biped->speed_x;
  if (y != 0)
    player->biped->pos.y += player->biped->speed_y;
}

void		input(t_world *world)
{
  Uint8		*keys;
  Uint8		mouse;
  int		x;
  int		y;
  SDL_Event	event;
  static int	last_state;

  keys = SDL_GetKeyState(NULL);
  if (keys[SDLK_UP])
    move_player(world->player, 0, -1);
  if (keys[SDLK_DOWN])
    move_player(world->player, 0, 1);
  if (keys[SDLK_RIGHT])
    move_player(world->player, 1, 0);
  if (keys[SDLK_LEFT])
    move_player(world->player, -1, 0);
  mouse = SDL_GetMouseState(&x, &y);
  world->reticle->pos.x = x - (world->reticle->sprite->size / 2);
  world->reticle->pos.y = y - (world->reticle->sprite->size / 2);
  if (mouse & SDL_BUTTON(1))
    {
      if (last_state)
	{
	  last_state = 0;
	  shoot(world);
	}
    }
  else
    last_state = 1;
  while (SDL_PollEvent(&event))
    {
      if (event.type == SDL_QUIT)
	exit(0);
    }
  stop_player(world->player);
  apply_speed_player(world->player, 1, 1);
}
